package com.mcj.demo;

import com.alibaba.fastjson2.JSON;
import com.mcj.entity.Author;
import com.mcj.entity.Book;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamDemo01 {
	
	public static void main(String[] args) {
		test32();
	}
	
	// map 将Optional中的对象类型转换
	private static void test32() {
		Optional<Author> authorOptional = getAuthorOptional();
		authorOptional.map(Author::getBooks).ifPresent(System.out::println);
	}
	
	// isPresent 判断Optional中的对象是否为空
	private static void test31() {
		Optional<Author> authorOptional = getAuthorOptional();
		System.out.println(authorOptional.isPresent());
		
	}
	
	// filter 按条件过滤Optional
	private static void test30() {
		Optional<Author> authorOptional = getAuthorOptional();
		Optional<Author> author = authorOptional.filter(author1 -> author1.getAge() > 31);
		System.out.println(author);
		
		authorOptional.filter(author1 -> author1.getAge() > 31).ifPresent(author2 -> System.out.println(author2.getName()));
	}
	
	// orElseThrow 从Optional对象中取值 如果为空则抛出自定义异常
	private static void test29() {
		Optional<Author> authorOptional = getAuthorOptional();
		Author author = authorOptional.orElseThrow(() -> new RuntimeException("空对象"));
		System.out.println(author);
	}
	
	// orElseGet 从Optional对象中取值 如果为空则返回自定义对象
	private static void test28() {
		Optional<Author> authorOptional = getAuthorOptional();
		Author author = authorOptional.orElseGet(() -> new Author(2L, "亚索", 15, "狂风也追逐不上他的思考速度", null));
		System.out.println(author);
	}
	
	
	private static Optional<Author> getAuthorOptional() {
		Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
		ArrayList<Book> books = new ArrayList<>();
		books.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
		books.add(new Book(4L,"吹或不吹","爱情,个人传记",56,"一个哲学家的恋爱观注定很难把他所在的时代理解"));
		author.setBooks(books);
		return Optional.ofNullable(author);
	}
	
	// ofNullable 将对象封装成Optional
	private static void test27() {
		Author author = getAuthors().get(0);
		Optional<Author> authorOptional = Optional.ofNullable(author);
		authorOptional.ifPresent(author1 -> System.out.println(author1.getName()));
	}
	
	// reduce 单参数
	private static void test26() {
		// 使用reduce求所有作者年龄中的最小值
		List<Author> authors = getAuthors();
		Optional<Integer> optionalInteger = authors.stream()
				.map(Author::getAge)
				.distinct()
				.reduce((result, element) -> result < element ? result : element);
		optionalInteger.ifPresent(System.out::println);
	}
	
	// reduce 双参数
	private static void test25() {
		// 使用reduce求所有作者年龄中的最小值
		List<Author> authors = getAuthors();
		Integer integerReduce = authors.stream()
				.map(Author::getAge)
				.distinct()
				.reduce(Integer.MAX_VALUE, (result, element) -> result < element ? result : element);
		System.out.println(integerReduce);
	}
	
	// reduce
	private static void test24() {
		// 使用reduce求所有作者年龄中的最大值
		List<Author> authors = getAuthors();
		Integer integerReduce = authors.stream()
				.map(Author::getAge)
				.distinct()
				.reduce(Integer.MIN_VALUE, (result, element) -> result > element ? result : element);
		System.out.println(integerReduce);
	}
	
	// reduce
	private static void test23() {
		// 使用reduce求所有作者年龄的和
		List<Author> authors = getAuthors();
		Integer integerReduce = authors.stream()
				.distinct()
				.map(Author::getAge)
				.reduce(0, Integer::sum);
		System.out.println(integerReduce);
	}
	
	// findFirst 从满足条件的流中 获取第一个元素
	private static void test22() {
		// 获取一个年龄最小的作家，并输出他的姓名
		List<Author> authors = getAuthors();
		Optional<Author> optionalAuthor = authors.stream()
				.sorted(Comparator.comparingInt(Author::getAge))
				.findFirst();
		optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
	}
	
	// findAny 从满足条件的流中 随机获取一个元素
	private static void test21() {
		// 获取任意一个大于18岁的作家，如果存在就输出名字
		List<Author> authors = getAuthors();
		Optional<Author> optionalAuthor = authors.stream()
				.filter(author -> author.getAge() > 18)
				.findAny();
		optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
	}
	
	// noneMatch 所有元素都不符合条件 返回true
	private static void test20() {
		// 判断所有作家是否都没有超过100岁
		List<Author> authors = getAuthors();
		System.out.println(authors.stream()
				.noneMatch(author -> author.getAge() > 100));
	}
	
	// allMatch 需要所有元素都满足条件 才返回true
	private static void test19() {
		// 判断所有作家是否都是成年人
		List<Author> authors = getAuthors();
		System.out.println(authors.stream()
				.allMatch(author -> author.getAge() >= 18));
	}
	
	// anyMatch 只要有任意满足条件的 就返回true
	private static void test18() {
		// 判断是否有年龄在29岁以上的作家
		List<Author> authors = getAuthors();
		System.out.println(authors.stream()
				.anyMatch(author -> author.getAge() > 29));
	}
	
	// Collectors.toMap 该方法需要两个参数 分别定义key、value的转换规则
	private static void test17() {
		// 获取一个Map集合，key为作者名，value为List<Book>
		List<Author> authors = getAuthors();
		Map<String, List<Book>> bookMap = authors.stream()
				.distinct()
				.collect(Collectors.toMap(Author::getName,
						author -> author.getBooks().stream().distinct().collect(Collectors.toList()))
				);
		System.out.println(JSON.toJSON(bookMap));
	}
	
	// Collectors.toSet()
	private static void test16() {
		// 获取一个存放所有书名的Set集合
		List<Author> authors = getAuthors();
		Set<String> bookSet = authors.stream()
				.flatMap(author -> author.getBooks().stream())
				.map(Book::getName)
				.collect(Collectors.toSet());
		System.out.println(JSON.toJSON(bookSet));
	}
	
	// Collectors.toList()
	private static void test15() {
		// 获取一个存放所有作者名字的List集合
		List<Author> authors = getAuthors();
		List<String> authorNameList = authors.stream()
				.distinct()
				.map(Author::getName)
				.collect(Collectors.toList());
		authorNameList.forEach(System.out::println);
	}
	
	// max min
	private static void test14() {
		// 分别获取这些作家所出书籍中的最高分和最低分
		List<Author> authors = getAuthors();
		authors.stream()
				.distinct()
				.forEach(author ->
						System.out.println(author.getName() + "-" +
								author.getBooks().stream()
										.map(Book::getScore)
										.max((o1, o2) -> o1 - o2)
										.get()
						)
				);
		
		System.out.println(authors.stream()
				.flatMap(author -> author.getBooks().stream())
				.map(Book::getScore)
				.max((o1, o2) -> o1 - o2));
	}
	
	// count
	private static void test13() {
		// 打印这些作家的作品数目，注意去重
		List<Author> authors = getAuthors();
		System.out.println(authors.stream()
				.flatMap(author -> author.getBooks().stream())
				.distinct()
				.count());
		
		// 分别打印这些作家的作品数目，注意去重
		authors.stream()
				.distinct()
				.forEach(author -> {
					System.out.println(author.getName() + "-" + author.getBooks().stream().distinct().count());
				});
	}
	
	// forEach
	private static void test12() {
		// 输出所有作家名字
		List<Author> authors = getAuthors();
		authors.stream()
				.map(Author::getName)
				.distinct()
				.forEach(System.out::println);
	}
	
	// flatMap 连续类型转换处理
	private static void test11() {
		// 打印现有数据的所有分类，要求对分类进行去重，不能出现这种格式：哲学，爱情(应拆分成两个基础类别)
		List<Author> authors = getAuthors();
		authors.stream()
				.flatMap(author -> author.getBooks().stream())
				.distinct()
				.flatMap(book -> Arrays.stream(book.getCategory().split(",")))
				.distinct()
				.forEach(System.out::println);
	}
	
	// flatMap 类型转换处理 将流转换成其他类型的流
	private static void test10() {
		// 打印所有书籍的名字，要求对重复元素进行去重
		List<Author> authors = getAuthors();
		authors.stream()
				.flatMap(author -> author.getBooks().stream())
				.distinct()
				.forEach(book -> System.out.println(book.getName()));
	}
	
	// skip 跳过操作 跳过前n个元素 保留其余元素
	private static void test09() {
		// 打印除了年龄最大的作家以外的其他作家，要求不能有重复元素，并且按照年龄降序排序
		List<Author> authors = getAuthors();
		authors.stream()
				.distinct()
				.sorted((o1, o2) -> o2.getAge() - o1.getAge())
				.skip(1)
				.forEach(author -> System.out.println(author.getAge() + "-" + author.getName()));
	}
	
	// limit 截取操作 保留前n个
	private static void test08() {
		// 对流中元素按照年龄进行降序排序，并且要求不能有重复元素，然后打印其中年龄最大的两个作家的姓名
		List<Author> authors = getAuthors();
		authors.stream()
				.distinct()
				.sorted((o1, o2) -> o2.getAge() - o1.getAge())
				.limit(2)
				.forEach(author -> System.out.println(author.getAge() + "-" + author.getName()));
	}
	
	// sort 排序操作
	private static void test07() {
		// 对流中元素按照年龄进行降序排序，并且要求不能有重复元素
		List<Author> authors = getAuthors();
		authors.stream()
				.sorted((o1, o2) -> o2.getAge() - o1.getAge())
				.distinct()
				.forEach(author -> System.out.println(author.getAge() + "-" + author.getName()));
	}
	
	// distinct 去重操作 默认调用Object.equals() 可以重写对象中的equals() @EqualsAndHashCode
	private static void test06() {
		// 打印所有作家的姓名，并且要求其中不能有重复元素
		List<Author> authors = getAuthors();
		authors.stream()
				.distinct()
				.forEach(author -> System.out.println(author.getName()));
	}
	
	// map 类型转换处理
	private static void test05() {
		// 打印所有作家的姓名
		List<Author> authors = getAuthors();
		// 类型转换
		authors.stream()
				.map(Author::getName)
				.forEach(System.out::println);
		// 类型转换后处理数据
		authors.stream()
				.map(Author::getAge)
				.map(age->age + 10)
				.forEach(System.out::println);
	}
	
	// filter
	private static void test04() {
		// 打印所有姓名长度大于1的作家姓名
		List<Author> authors = getAuthors();
		authors.stream()
				.distinct()
				.filter(author -> author.getName().length() > 1)
				.forEach(author -> System.out.println(author.getName()));
	}
	
	// 双列集合 map集合
	private static void test03() {
		Map<String,Integer> map = new HashMap<>();
		map.put("蜡笔小新",19);
		map.put("黑子",17);
		map.put("日向翔阳",16);
		
		Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
		Stream<Map.Entry<String, Integer>> stream1 = entrySet.stream();
		Stream<Map.Entry<String, Integer>> stream2 = map.entrySet().stream();
		
		stream1
				.filter(stringIntegerEntry -> stringIntegerEntry.getValue() < 18)
				.forEach(stringIntegerEntry -> System.out.println(stringIntegerEntry.getKey()));
	}
	
	// 数组 创建流的两种方式
	private static void test02() {
		Integer[] arr = {1,2,3,4,5};
		Stream<Integer> stream1 = Arrays.stream(arr);
		Stream<Integer> stream2 = Stream.of(arr);		// 实际也是调用Arrays.stream(values)
		
		stream1
				.filter(integer -> integer < 2)
				.forEach(System.out::println);
		stream2
				.forEach(System.out::println);
	}
	
	// 集合
	private static void test01() {
		List<Author> authors = getAuthors();
		authors.stream()
				.distinct()		// 去重
				.filter(author -> author.getAge() < 18)
				.forEach(author -> System.out.println(author.getName()));
	}
	
	private static List<Author> getAuthors() {
		//数据初始化
		Author author1 = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
		Author author2 = new Author(2L,"亚索",15,"狂风也追逐不上他的思考速度",null);
		Author author3 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);
		Author author4 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);
		
		//书籍列表
		List<Book> books1 = new ArrayList<>();
		List<Book> books2 = new ArrayList<>();
		List<Book> books3 = new ArrayList<>();
		
		books1.add(new Book(1L,"刀的两侧是光明与黑暗","哲学,爱情",88,"用一把刀划分了爱恨"));
		books1.add(new Book(2L,"一个人不能死在同一把刀下","个人成长,爱情",99,"讲述如何从失败中明悟真理"));
		
		books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
		books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
		books2.add(new Book(4L,"吹或不吹","爱情,个人传记",56,"一个哲学家的恋爱观注定很难把他所在的时代理解"));
		
		books3.add(new Book(5L,"你的剑就是我的剑","爱情",56,"无法想象一个武者能对他的伴侣这么的宽容"));
		books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢？"));
		books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢？"));
		
		author1.setBooks(books1);
		author2.setBooks(books2);
		author3.setBooks(books3);
		author4.setBooks(books3);
		
		return new ArrayList<>(Arrays.asList(author1,author2,author3,author4));
	}
}
